package com.fitness.dao;

import com.fitness.entity.Member;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 会员表数据访问对象，继承 BaseDAO，实现会员相关数据库操作
 */
public class MemberDAO extends BaseDAO {

    /**
     * 根据会员ID查询会员信息
     * @param memberId 会员ID
     * @return 会员实体对象（不存在则为 null）
     */
    public Member getMemberById(int memberId) {
        String sql = "SELECT * FROM 会员表 WHERE 会员ID = ?";
        ResultSet rs = executeQuery(sql, memberId);
        try {
            if (rs != null && rs.next()) {
                Member member = new Member();
                member.setMemberId(rs.getInt("会员ID"));
                member.setMemberName(rs.getString("会员姓名"));
                member.setPhone(rs.getString("联系电话"));
                member.setPoints(rs.getInt("积分"));
                member.setMembershipLevel(rs.getString("会员等级"));
                member.setDiscountRate(rs.getDouble("折扣率"));
                return member;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(null, null, rs);
        }
        return null;
    }

    /**
     * 插入会员信息
     * @param member 会员实体对象
     * @return 插入是否成功（true/false）
     */
    public boolean insertMember(Member member) {
        String sql = "INSERT INTO 会员表(会员姓名, 联系电话, 积分, 会员等级, 折扣率) " +
                "VALUES (?, ?, ?, ?, ?)";
        int affectedRows = executeUpdate(sql,
                member.getMemberName(),
                member.getPhone(),
                member.getPoints(),
                member.getMembershipLevel(),
                member.getDiscountRate());
        return affectedRows > 0;
    }

    /**
     * 查询所有会员信息
     * @return 会员列表
     */
    public List<Member> getMemberList() {
        List<Member> memberList = new ArrayList<>();
        String sql = "SELECT * FROM 会员表";
        ResultSet rs = executeQuery(sql);
        try {
            while (rs != null && rs.next()) {
                Member member = new Member();
                member.setMemberId(rs.getInt("会员ID"));
                member.setMemberName(rs.getString("会员姓名"));
                member.setPhone(rs.getString("联系电话"));
                member.setPoints(rs.getInt("积分"));
                member.setMembershipLevel(rs.getString("会员等级"));
                member.setDiscountRate(rs.getDouble("折扣率"));
                memberList.add(member);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources(null, null, rs);
        }
        return memberList;
    }

    public boolean deleteMember(int memberId) {
        String sql = "DELETE FROM 会员表 WHERE 会员ID = ?";
        int affectedRows = executeUpdate(sql, memberId);
        return affectedRows > 0;
    }
}